<?php
/**
 * 产品 model 类
 *
 * @author <judasnow@gmail.com>
 */
require_once( APPPATH . 'models/base_model.php' );

class Product_model extends base_model{
	private $_table_name;
	private $_CI;
	public function __construct(){
		$this->_table_name = 'product';
		parent::__construct( $this->_table_name );
		$this->_CI =& get_instance();
		$this->_CI->load->model( 'Product_at_spec_class_model' , '' , TRUE );
	}

	public function find_all( $cond = array() , $order_by = '' , $per_pager = '' , $offset = '' , $search_sql = '' ){
		 if( !empty( $search_sql ) ){
			 $sql_limit = !empty( $per_pager ) ? "LIMIT $per_pager" : '';
			 $sql_offset = !empty( $offset ) ? " OFFSET $offset" : ''; 
			 $sql = $search_sql . " $sql_limit $sql_offset";
			 $q = $this->db->query( $sql );
			 $ori_product_infos = $q->result_array();	 
		 }else{
			 if( !empty( $order_by ) ){
				 $this->db->order_by( $order_by['title'] , $order_by['order'] );
			 }
			 if( !empty( $cond ) ){
				 $this->db->where( $cond );		 
			 }
			 $res = $this->_CI->db->get( $this->_table_name , $per_pager , $offset );
			 $ori_product_infos = $res->result_array();
		 }
		 return $this->get_product_at_spec_class_by_product( $ori_product_infos );
	}

	//获得全部的商品列表
	public function get_product_list_all(){
		 //原始的商品信息
		 $ori_product_infos = $this->find_all();
		 return $this->get_product_at_spec_class_by_product( $ori_product_infos );
	}

	/*
	 * 获得商品所属的服务的信息
	 *
	 * @param array $products 需要获取信息的商品的数组
	 * @param array 添加了相应信息之后的商品信息数组
	 */
	private function get_product_at_spec_class_by_product( $ori_product_infos ){
		 $product_infos = array();
		 //获得商品所属的服务的信息
		 foreach( $ori_product_infos as $no=>$product_info ){
			 $product_infos[$no] = $product_info;
			 //为之添加服务信息
			 $product_infos[$no]['class_info'] = $this->_CI->Product_at_spec_class_model->find( 
				 array( 'product_id'=>$product_info['product_id'] ) );
		 }
		 return $product_infos;
	}

	public function get_product_title_by_id( $product_id ){
		$this->db->where( 'product_id' , $product_id );
		$q = $this->db->get( 'product' );
		if( $q->num_rows() != 1 ){
			 throw new Exception( '获取商品信息异常 SQL=[' . $this->db->last_query() . ']' );
		}
		$res = $q->result_array();
		return $res[0]['title'];
	}
}
